package com.huan.vertxle.service.impl;

import com.huan.vertxle.dao.ScanCodeDao;
import com.huan.vertxle.enums.WareOperaTypeEnum;
import com.huan.vertxle.initialization.RedisInit;
import com.huan.vertxle.model.ScanCode;
import com.huan.vertxle.service.IScanCodeService;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.redis.client.Command;
import io.vertx.redis.client.Request;
import io.vertx.redis.client.Response;

/**
 * @author huan
 */
public class ScanCodeServiceImpl implements IScanCodeService {
  private final InternalLogger logger = Slf4JLoggerFactory.getInstance(this.getClass().getName());

  @Override
  public void processingScan(RoutingContext routingContext) {
    JsonObject bodyAsJson = routingContext.getBodyAsJson();
    HttpServerResponse response = routingContext.response();
    response.putHeader("content-type", "text/plain");
    logger.info(bodyAsJson.toString());
    int key = 1;
    RedisInit.client.send(Request.cmd(Command.SET).arg(key).arg("huanhuan")).compose(event -> this.delRedis(key))
      .onSuccess(res -> {
        logger.info("success:{}", res);
        response.end("success");
      }).onFailure(throwable -> {
      logger.error("error:{}", throwable.getMessage());
      response.end("error");
    });
  }

  private Future<Response> delRedis(int key) {
    Promise<Response> promise = Promise.promise();
    RedisInit.client.send(Request.cmd(Command.DEL).arg(key)).onSuccess(promise::complete).onFailure(promise::fail);
    return promise.future();
  }

  @Override
  public void dealScanData(String data, Message<String> msg) {
    JsonObject jsonObject;
    try {
      jsonObject = new JsonObject(data);
    } catch (Exception e) {
      logger.warn("无效传输数据:{}", e.getMessage());
      msg.fail(500, "无效的数据类型,请检查!");
      return;
    }
    String type = jsonObject.getString("type");
    if (StringUtil.isNullOrEmpty(type)) {
      msg.fail(500, "无效的数据类型,请检查!");
      return;
    }
    jsonObject.remove("type");
    // 扫描入库操作
    if (WareOperaTypeEnum.SCAN_STORAGE.name().equalsIgnoreCase(type)) {
      ScanCode scanCode = Json.decodeValue(jsonObject.toString(), ScanCode.class);
      ScanCodeDao scanCodeDao = ScanCodeDao.getInstance();
      scanCodeDao.enterWarehouse(scanCode).onSuccess(event -> {
        Long id = event.iterator().next().getLong("id");
        // 获取插入的id值
        msg.reply(id);
      }).onFailure(event -> msg.fail(500, "入库操作异常" + event.getMessage()));
    }
  }
}
